package com.sm.controller;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.sm.model.*;
import com.sm.service.*;
import com.sm.util.PageBean;
import com.sm.util.PageResult;
import com.sm.vo.*;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import com.sm.util.Msg;

@Controller
@RequestMapping("/home")
public class XymHomeController {

	@Autowired
	private BannerService bannerService;
	@Autowired
	private FirstDirectoryService firstDirectoryService;
	@Autowired
	private VideoCourseService videoCourseService;
	@Autowired
	private ActivitiesService activitiesService;
	@Autowired
	private UserService userService;
	@Autowired
	private SearchHistoryService searchHistoryService;
	@Autowired
	private HomeRecordService homeRecordService;
	@Autowired
	private GoodsRecordService goodsRecordService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private SecondSortService secondSortService;
	@Autowired
	private HomeIconService homeIconService;
    @Autowired
    private DataCloudLibraryService dataCloudLibraryService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ListenService listenService;
    @Autowired
	private HappyRequestService happyRequestService;
    @Autowired
	private HappySolveService happySolveService;
    @Autowired
    private AppConfigService appConfigService;
	/**
	 *	新APP查询首页的所有的一级类别和banner。
	 * @return
	 */
	@RequestMapping(value = "/category")
	@ResponseBody
	public Msg selectAllBanner(){

		//查询首页所有的轮播图
		List<Banner> banner = bannerService.selectBannerPic(0);

		//查询首页的所有的一级类别
        List<HomeIcon> homeIcons = homeIconService.selectHomeIcons();
        return Msg.success().add("banner", banner).add("homeIcons", homeIcons);
	}


	/**
	 *	根据非类别icon查询课程列表(小图标打开之后的列表)
	 */
	@RequestMapping("/getNotDirectory")
	@ResponseBody
    @CrossOrigin
	public Msg selectVideoByFirstDirectory(@RequestParam("iconId")Integer iconId,Integer currentPage,Integer pageSize,@RequestParam(value = "categoryId",required = false)Integer categoryId) {
		PageResult pageResult = null;
		if (iconId == 1){
	        //免费体验
			pageResult = videoCourseService.selectFreeVideo(currentPage, pageSize);
		}else if (iconId ==2){
	        //最新课程
            pageResult = videoCourseService.selectNewVideo(currentPage, pageSize);
        }else if (iconId ==3){
	        //最热课程
            pageResult = videoCourseService.selectHottestVideo(currentPage, pageSize);
        }else if (iconId == 4){
	        //全部课程
            pageResult = videoCourseService.selectAllVideo(currentPage, pageSize);
        }else if (iconId ==5){
	        //资料云库
			pageResult = dataCloudLibraryService.selectDataList(currentPage, pageSize,categoryId);
        }
    	return Msg.success().add("videoCourses", pageResult);
	}

	/**
	 * 根据一级类别icon查询课程列表(小图标打开之后的列表)
	 */
	@RequestMapping("/getByDirectory")
	@ResponseBody
    @CrossOrigin
	public Msg getByDirectory(@RequestParam("firstId")Integer firstId,@RequestParam("currentPage")Integer currentPage,@RequestParam("pageSize")Integer pageSize,@RequestParam(value = "secondId",required = false)Integer secondId){
		if (ObjectUtils.isEmpty(firstId)){
			return Msg.fail().add("msg","参数为空");
		}
        PageResult pageResult = videoCourseService.selectVideoByFirsetAndSecond(firstId, secondId,currentPage,pageSize);
        if (ObjectUtils.isEmpty(pageResult)){
            return Msg.fail().add("msg","暂无数据");
        }
        return Msg.success(pageResult);
    }

    /**
     * 首页模块拼接（近期活动+免费体验+精品推荐+名家讲坛+每日一听）
     */
    @RequestMapping("/homeMember")
    @ResponseBody
    public Msg homeMember(@RequestParam(value = "teacherName",required = false)String teacherName){
        List<HomeMemberVo> vos = new ArrayList<>();
        //拼接幸福问答
        AppConfig happyRequestHomeNum = appConfigService.getByKey("happy_request_home_num");
        HomeMemberVo xfwd = new HomeMemberVo("xfwd");
        xfwd.setAsName("幸福问答");
        List<HappyRequest> list = happyRequestService.getBotiqueList(Integer.valueOf(happyRequestHomeNum.getValue()));
        for (HappyRequest request : list) {
            User user = userService.selectAvatarAndNickName(request.getRequestUser());
            if (ObjectUtil.isNotEmpty(user.getHeadLink())){
                request.setExt1(user.getHeadLink());
            }
            request.setExt2(user.getNickName());
            //粘贴对应的回答内容
			HappySolve happySolve = happySolveService.selectOneContent(request.getRequestId());
			if (ObjectUtil.isNotEmpty(happySolve)){
				request.setContent(happySolve.getContent());
			}
		}
        if (!ObjectUtils.isEmpty(list)){
            xfwd.setList(list);
        }
        vos.add(xfwd);
        //拼接免费体验
        AppConfig homeFreeVideoNum = appConfigService.getByKey("home_free_video_num");
        HomeMemberVo free = new HomeMemberVo("mfty");
        free.setAsName("免费体验");
        PageResult pageResult = videoCourseService.selectFreeVideo(1, Integer.valueOf(homeFreeVideoNum.getValue()));
        free.setList(pageResult.getRows());
        vos.add(free);
        //拼接精品推荐
        AppConfig homeQualityVideoNum = appConfigService.getByKey("home_quality_video_num");
        HomeMemberVo jptj = new HomeMemberVo("jptj");
        jptj.setAsName("精品推荐");
        List<VideoCourse> videoCourses = videoCourseService.selectCourseBoutique(1,Integer.valueOf(homeQualityVideoNum.getValue())).getRows();
        jptj.setList(videoCourses);
        vos.add(jptj);
        //拼接名家讲坛
        AppConfig homeFamousNum = appConfigService.getByKey("home_famous_num");
        HomeMemberVo teacherVideos = new HomeMemberVo("mjjt");
        teacherVideos.setAsName("名家讲坛");
		teacherVideos.setFirstId(4);
		List<SecondDirectory> secondDirectories = videoCourseService.selectSecondByFirstDirectory(4);
		List<SecondDirectory> directories = secondDirectories.stream().limit(Integer.valueOf(homeFamousNum.getValue())).collect(Collectors.toList());
		teacherVideos.setList(directories);
        vos.add(teacherVideos);
        //拼接每日一听
        AppConfig homeSoundNum = appConfigService.getByKey("home_sound_num");
        HomeMemberVo listen = new HomeMemberVo("mryt");
        listen.setAsName("每日一听");
        listen.setList(listenService.pageQuery(1,Integer.valueOf(homeSoundNum.getValue()),null).getRows());
        vos.add(listen);
        return Msg.success(vos);
    }



	/**
	 *	根据一级类别查询一级类别的所有二级类别
	 * @param firstDirectoryId	一级类别id
	 * @return
	 */
	@RequestMapping("/selectSecondCategory")
	@ResponseBody
	public Msg selectSecondCategory(Integer firstDirectoryId) {
		if(firstDirectoryId == null) {
			return Msg.fail().add("msg", "数据异常，请重试");
		}
		//通过视频课程的一级类别id查询其包含的所有的二级类别。
		List<SecondDirectory> secondDirectorys = videoCourseService.selectSecondByFirstDirectory(firstDirectoryId);
		return Msg.success().add("secondDirectorys", secondDirectorys);
	}


    /**
     * 首页查看更多
     */
    @RequestMapping("/lookMore")
	@ResponseBody
    public Msg lookMore(String name,Integer currentPage,Integer pageSize,@RequestParam(value = "secondId",required = false)Integer secondId){
        PageResult pageResult = null;
        switch (name){
            case "jqhd":
                pageResult = activitiesService.getList(currentPage, pageSize);
                break;
            case "mfty":
                pageResult = videoCourseService.selectFreeVideo(currentPage,pageSize);
                break;
            case "jptj":
                pageResult = videoCourseService.selectCourseBoutique(currentPage, pageSize);
                break;
            case "mjjt":
                pageResult = videoCourseService.selectVideoByFirsetAndSecond(4,secondId,currentPage,pageSize);
                break;
            case "mryt":
                pageResult = listenService.pageQuery(currentPage,pageSize,null);
                break;
        }
        if (ObjectUtils.isEmpty(pageResult)){
            return Msg.success().add("msg","暂无数据");
        }
        return Msg.success(pageResult);
    }


    /**
     * 首页--资料云库列表页
     */
    @RequestMapping("/dataCloudList")
    @ResponseBody
    public Msg dataCloudList(Integer currentPage,Integer pageSize,@RequestParam(value = "categoryId",required = false)Integer categoryId){
        PageResult pageResult = dataCloudLibraryService.selectDataList(currentPage, pageSize, categoryId);
        if (ObjectUtils.isEmpty(pageResult)){
            return Msg.success().add("msg","暂无数据");
        }
        return Msg.success(pageResult);
    }

	/**
	 * 首页资料云库--列表页目录
	 */
	@RequestMapping("/dataCategories")
	@ResponseBody
	public Msg dataCategories(){
		List<DataCloudLibraryCategory> dataCloudLibraryCategories = dataCloudLibraryService.dataCategories();
		if (ObjectUtils.isEmpty(dataCloudLibraryCategories)){
			return Msg.success().add("msg","暂无数据");
		}
		return Msg.success(dataCloudLibraryCategories);
	}



	/**
	 *	全局搜索根据搜索内容搜索课程视频、商品、活动、每日一听、资料云库并将搜索内容插入数据库中
	 * @param searchContent			输入的搜索内容
	 * @param userId				用户id
	 * @return
	 */
	@RequestMapping("/searchVideo")
	@ResponseBody
	public Msg searchVideo(String searchContent, Integer userId) {
		if(userId == null) {
			return Msg.fail().add("msg", "数据异常请重试。");
		}
		if(searchContent == null || searchContent.equals("")) {
			return Msg.fail().add("msg", "搜索内容不能为空");
		}

		//通过用户id查询用户的搜索历史记录
		List<SearchHistory> searchHistorys = searchHistoryService.selectsearchByUserId(userId);

		if(searchHistorys != null && searchHistorys.size() != 0) {
			boolean flag = false;//定义一个搜索记录不存在
			for (SearchHistory searchHistory : searchHistorys) {
				if(searchHistory.getCont().equals(searchContent)) {//如果存在搜索过的记录
					searchHistory.setSearchTime(new Date());//将历史记录的时间修改成最新的。
					searchHistoryService.updateByPrimaryKeySelective(searchHistory);
					flag = true;//将开关，设置成存在。
					break;
				}
			}

			if(flag == false) {
				//将搜索内容存入到数据库中
				SearchHistory searchHistory = new SearchHistory();
				searchHistory.setUserId(userId);//设置用户id
				searchHistory.setCont(searchContent);//设置搜索内容
				searchHistory.setSearchTime(new Date());//设置当前时间
				searchHistoryService.insertSelective(searchHistory);//将搜索内容插入数据库
			}

		}else {
			//将搜索内容存入到数据库中
			SearchHistory searchHistory = new SearchHistory();
			searchHistory.setUserId(userId);//设置用户id
			searchHistory.setCont(searchContent);//设置搜索内容
			searchHistory.setSearchTime(new Date());//设置当前时间
			searchHistoryService.insertSelective(searchHistory);//将搜索内容插入数据库
		}

		List<SearchVo> searchVos = new ArrayList<>();

		//根据搜索内容搜索课程视频
		List<SearchResult> videos = new ArrayList<>();
		List<VideoCourse> videoCourses = videoCourseService.searchVideo(searchContent,1,10).getRows();
		for (VideoCourse v : videoCourses) {
            SearchResult searchResult = new SearchResult(v.getVideoCourseId(), v.getCourseName());
            FirstDirectory firstDirectory = firstDirectoryService.selectOne(v.getFirstDirectoryId());
            searchResult.setIfSchool(firstDirectory.getIfSchool());
            videos.add(searchResult);
		}
		searchVos.add(new SearchVo(1,"课程",videos));

		//根据搜索内容搜索商品
		List<SearchResult> goods = new ArrayList<>();
		List<Goods> goodsSearchs = goodsService.selectGoodsByCont(searchContent,1,10).getRows();
		for (Goods g : goodsSearchs) {
			goods.add(new SearchResult(g.getGoodsId(),g.getGoodsName()));
		}
		searchVos.add(new SearchVo(2,"商品",goods));

		//根据搜索内容搜索活动
		List<SearchResult> activitys = new ArrayList<>();
		List<Activities> searchActivities = activitiesService.searchActivities(searchContent,1,10).getRows();
		for (Activities act : searchActivities) {
			activitys.add(new SearchResult(act.getActivitiesId(),act.getTitle()));
		}
		searchVos.add(new SearchVo(3,"活动",activitys));

		//根据搜索内容搜索每日一听
		List<SearchResult> listens = new ArrayList<>();
		List<ListenEveryday> searchListens = listenService.pageQuery(1, 10, searchContent).getRows();
		for (ListenEveryday listen : searchListens) {
			listens.add(new SearchResult(listen.getListenId(),listen.getTitle()));
		}
		searchVos.add(new SearchVo(4,"每日一听",listens));

		//根据搜索内容搜索资料云库
		List<SearchResult> dataClouds = new ArrayList<>();
		List<DataCloudLibrary> dataCloudSearchs = dataCloudLibraryService.searchDataCloud(searchContent, 1, 10).getRows();
		for (DataCloudLibrary data : dataCloudSearchs) {
			dataClouds.add(new SearchResult(data.getId(),data.getTitle()));
		}
		searchVos.add(new SearchVo(5,"资料云库",dataClouds));
		return Msg.success().add("searchVos", searchVos);
	}


	/**
	 *	清空搜索历史记录
	 * @param userId
	 * @return
	 */
	@RequestMapping("/clearSearch")
	@ResponseBody
	public Msg clearSearch(Integer userId) {
		//删除所有的历史记录
		int count = searchHistoryService.clearSearchByUserId(userId);
		return Msg.success().add("msg", "删除成功");
		}



	/**
	 *	根据用户id查询用户的搜索记录
	 * @param userId	用户id
	 * @return
	 */
	@RequestMapping("/selectSearch")
	@ResponseBody
	public Msg selectHomeSearch(Integer userId) {
		if(userId == null) {
			return Msg.fail().add("msg", "数据异常请重试。");
		}
		//通过用户id查询用户的搜索历史记录并根据时间排序
		List<SearchHistory> searchHistories = searchHistoryService.selectsearchByUserId(userId);
		return Msg.success().add("searchHistories", searchHistories);
	}


	/**
	 *	根据视频课程的一级类别和视频课程的二级类别查询二级类别下的所有视频课程。
	 * @param firstDirectoryId		视频课程的一级类别id
	 * @return
	 */
	@RequestMapping("/selectSecondVideoByFirstId")
	@ResponseBody
	public Msg selectSecondVideoByFirstId(Integer firstDirectoryId) {

		if(firstDirectoryId == null) {
			return Msg.fail().add("msg", "数据异常，请重试！");
		}

		//根据视频一级类别id查询其所有的二级类别。
		List<SecondDirectory> secondDirectorys = videoCourseService.selectSecondByFirstDirectory(firstDirectoryId);
		if(secondDirectorys == null || secondDirectorys.size() == 0) {
			return Msg.fail().add("msg", "数据异常，请重试");
		}else {
			//创建一个集合存放所有的二级类别以及其下的所有视频的实体类
			List<SecondVideoVO> secondVideoVOs = new ArrayList<SecondVideoVO>();

			for (SecondDirectory secondDirectory : secondDirectorys) {//遍历所有的二级类别。
				//根据视频课程的一级类别id查询其下的每个二级类别id查询其所有的视频课程。
//				List<VideoCourse> videoCourses = videoCourseService.selectVideoByFirsetAndSecond(firstDirectoryId,secondDirectory.getSecondDirectoryId());

				//创建一个实体类存放二级类别以及其下的所有视频。
//				SecondVideoVO secondVideoVO = new SecondVideoVO(secondDirectory, videoCourses);
//				secondVideoVOs.add(secondVideoVO);//将实体类存放到集合中。
			}
			return Msg.success().add("secondVideoVOs", secondVideoVOs);
		}
	}


	/**
	 * 首页名家讲坛模块点击进入的列表页
	 */
	@RequestMapping("/clickHomeMjjt")
	@ResponseBody
	public Msg clickHomeMmjt( Integer secondId,Integer currentPage,Integer pageSize){
		if (secondId == null){
			return Msg.fail().add("msg","参数异常");
		}
		PageResult listBySecondId = videoCourseService.selectVideoByFirsetAndSecond(4,secondId, currentPage, pageSize);
		if (ObjectUtil.isEmpty(listBySecondId)){
			return Msg.success().add("msg","暂无数据");
		}
		return Msg.success(listBySecondId);
	}






}



